/*
 * @Description: Stay hungry，Stay foolish
 * @Author: Huccct
 * @Date: 2023-05-18 12:11:32
 * @LastEditors: 31309 3130945@qq.com
 * @LastEditTime: 2024-08-06 14:00:05
 */
// 二次封装axios
import axios from 'axios'
import {GET_TOKEN, SET_TOKEN} from '@/utils/token'
import router from "@/router";

import { ElMessage } from 'element-plus'

const request = axios.create({
        baseURL: import.meta.env.VITE_SERVICE_URL,
        timeout: 60000,
        // 跨域时是否要发送cookie
        withCredentials: true,
        // 允许跨域请求的Orign
        headers:{//请求头，可以加上toekn等内容
            'Content-Type': 'application/json;charset=utf-8',
            'Authorization': 'Bearer '+GET_TOKEN(),

        }
    }
)

request.interceptors.request.use(

    config => {

        if (GET_TOKEN()!=null) {
            config.headers['Authorization']  ="Bearer "+GET_TOKEN()
        }
        return config;
    },
    error => {
        // 请求错误处理
        return Promise.reject(error);
    }


)

request.interceptors.response.use(
    (response) => {
        if (response.status === 200) {

            if(response.data.code=='10400'){
                ElMessage.error(response.data.errorMessage)
                // message.error(response.data.errorMessage,2);
                router.push({
                    path: "/"
                });
                return Promise.resolve();
            }else if(response.data.code=='10000') {
                if(response.data.token!=null&&response.data.token!=''){
                    SET_TOKEN(response.data.token);
                }
                return Promise.resolve(response.data)
            }else{
                return Promise.resolve(response.data)
            }

        } else {
            ElMessage.error("请求异常："+response.status)
            return Promise.reject(response.data)
        }
    },
    (error) => {
        console.log(error)
        if(error.code=='ERR_NETWORK'){

            ElMessage.error("服务器链接异常")
        }

        return Promise.reject(error)
    },
)




export default request
